from django.db import migrations


def add_missing_columns(apps, schema_editor):
    connection = schema_editor.connection
    with connection.cursor() as cursor:
        fixes = [
            ("deal_transaction_result", "sign_date", "DATE"),
            ("deal_bid_opening_record", "opening_time", "DATETIME"),
            ("deal_bid_opening_detail", "bid_price", "DECIMAL(15,2)"),
            ("deal_tender_clarification", "clarification_date", "DATETIME"),
            ("deal_bid_evaluation_result", "original_url", "VARCHAR(200)"),
        ]
        for table, column, ddl in fixes:
            try:
                cursor.execute(f"SHOW COLUMNS FROM {table} LIKE '{column}'")
                exists = cursor.fetchone()
            except Exception:
                exists = None
            if not exists:
                cursor.execute(f"ALTER TABLE {table} ADD COLUMN {column} {ddl}")


def noop_reverse(apps, schema_editor):
    pass


class Migration(migrations.Migration):
    dependencies = [
        ('deal', '0004_fix_bidcandidate_bid_price'),
    ]

    operations = [
        migrations.RunPython(add_missing_columns, noop_reverse),
    ]